package network;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Timer;

import bundle.BundleLayer;
import link.*;

public class NetworkLayer {

	static LinkLayer link;

	static SNACASD sd;

	static Neighbours neighbours;

	static Timer neighbourCheck;

	final static long TIMEOUTNEIGHBOURS = 10000;

	static BellmanFord bellman;

	static Router router;

	public static String myID;

	static Demux demux;

	static NetMessageHandler handler;

	public static void init(String ID, String server) {
		link = new LinkLayer(server);
		sd = new SNACASD(link, 10, 3);
		myID = sd.getUniqueName(ID);
		System.out.println("Name " + myID + " accepted.");
		sd.myName = myID;
		// retrieve the name of your computer
		String localname;
		try {
			localname = InetAddress.getLocalHost().getHostName();
			// tell it to the main hub
			link.send("server:" + myID + ":serverjoin:" + localname);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		neighbours = new Neighbours();
		System.err.println("Neighbours started");
		bellman = new BellmanFord(link);
		System.err.println("bellman started");
		router = new Router(link);
		System.err.println("router started");
		NeighbourTask neighbourTask = new NeighbourTask(neighbours);
		neighbourCheck = new Timer();
		neighbourCheck.schedule(neighbourTask, TIMEOUTNEIGHBOURS,
				TIMEOUTNEIGHBOURS);
		System.err.println("NeighboursCheck started");
		demux = new Demux();
		new Thread(demux).start();
		handler = new NetMessageHandler();
		new Thread(handler).start();
	}

	public static void send(String msg) {
		// System.out.println("Network " + msg);
		String[] splitMessage = msg.split(":");
		String outMSG = router.forgeNXTHOP(splitMessage[0], msg);
		if (!outMSG.equals("")) {
			link.send(outMSG);
		} else {
			System.err.println("Message stored for lack of a NXTHOP");
			BundleLayer.warehouse.addBundle(splitMessage[0], msg);
		}
	}

	public static synchronized Object[] getTargetList() {
		return bellman.via.keySet().toArray();
	}

	public static void receive(String msg) {
		handler.handleMessage(msg);
	}

	public static void showTable() {
		bellman.showTable();
	}

}
